package cn.itcast.utils;

import com.baidu.aip.face.AipFace;
import org.json.JSONArray;
import org.json.JSONObject;

import java.util.HashMap;

public class AipFaceHelper {

    //设置APPID/AK/SK
    private static final String APP_ID = "22837708";
    private static final String API_KEY = "0FEHfkABTAEFukUqfPWbzOiy";
    private static final String SECRET_KEY = "e09QQvZM8rrtvN1GAVXgIb5LK87Wi2qL";

    private static AipFace client = null;

    static {
        if (client == null) {
            client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
            client.setConnectionTimeoutInMillis(2000);
            client.setSocketTimeoutInMillis(60000);
        }
    }

    /**
     * 从百度云AI中根据图片查找用户绑定的id
     */
    public static String faceSearch(String image) {
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("quality_control", "LOW");// 图片质量控制
        options.put("liveness_control", "LOW");//活体检测控制
        options.put("max_user_num", "1"); // 查找后返回的用户数量,返回相似度最高的几个用户

        //调用api完成根据图片识别
        JSONObject res = client.search(image, "BASE64", "test_group", options);

        //解析返回值res
        if(res.has("error_code") && res.getInt("error_code")==0) {
            JSONObject result = res.getJSONObject("result");
            JSONArray userList = result.getJSONArray("user_list");
            if(userList.length()>0) {
                JSONObject user = userList.getJSONObject(0);
                return user.getString("user_id");
            }
        }
        return null;
    }
}
